/*
 * Marcoformas.java
 *
 * Created on 7 de octubre de 2007, 18:23
 */

package es.atareao.ferraplan.gui;
//
//********************************IMPORTACIONES*********************************
//
import es.atareao.alejandria.gui.ErrorDialog;
import es.atareao.queensboro.db.Conector;
import es.atareao.ferraplan.lib.Forma;
import java.sql.SQLException;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author  Propietario
 */
public class DialogFormas extends javax.swing.JFrame {
    //
    //********************************CONSTANTES********************************
    //
    /** A return status code - returned if Cancel button has been pressed */
    public static final int RET_CANCEL = 0;
    /** A return status code - returned if OK button has been pressed */
    public static final int RET_OK = 1;
    //
    public final static int OP_ADD=0;
    public final static int OP_EDIT=1;
    public final static int OP_DELETE=2;
    public final static int OP_VIEW=3;
    //
    //******************************CONSTRUCTORES*******************************
    //    
    /** Creates new form Marcoformas */
    public DialogFormas(Conector conector) {
        initComponents();
        this.setSize(610,630);
        this.setLocationRelativeTo(null);
        this.setConector(conector);
        this.refresca();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItemAñadir = new javax.swing.JMenuItem();
        jMenuItemEditar = new javax.swing.JMenuItem();
        jMenuItemConsultar = new javax.swing.JMenuItem();
        jMenuItemBorrar = new javax.swing.JMenuItem();
        jAceptar = new javax.swing.JButton();
        jCancelar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        jMenuItemAñadir.setText("Añadir");
        jMenuItemAñadir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemAñadirActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItemAñadir);

        jMenuItemEditar.setText("Editar");
        jMenuItemEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemEditarActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItemEditar);

        jMenuItemConsultar.setText("Consultar");
        jMenuItemConsultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemConsultarActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItemConsultar);

        jMenuItemBorrar.setText("Borrar");
        jMenuItemBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemBorrarActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItemBorrar);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/atareao/img/png/button_ok.png"))); // NOI18N
        jAceptar.setBorderPainted(false);
        jAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAceptarActionPerformed(evt);
            }
        });
        getContentPane().add(jAceptar, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 540, 50, 50));

        jCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/es/atareao/img/png/button_cancel.png"))); // NOI18N
        jCancelar.setBorderPainted(false);
        jCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCancelarActionPerformed(evt);
            }
        });
        getContentPane().add(jCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 540, 50, 50));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable1.setComponentPopupMenu(jPopupMenu1);
        jScrollPane1.setViewportView(jTable1);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 580, 520));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItemBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemBorrarActionPerformed
        this.operaciones(OP_DELETE);
    }//GEN-LAST:event_jMenuItemBorrarActionPerformed

    private void jMenuItemConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemConsultarActionPerformed
        this.operaciones(OP_VIEW);
    }//GEN-LAST:event_jMenuItemConsultarActionPerformed

    private void jMenuItemEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemEditarActionPerformed
        this.operaciones(OP_EDIT);
    }//GEN-LAST:event_jMenuItemEditarActionPerformed

    private void jMenuItemAñadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemAñadirActionPerformed
        this.operaciones(OP_ADD);
    }//GEN-LAST:event_jMenuItemAñadirActionPerformed

    private void jCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCancelarActionPerformed
// TODO add your handling code here:
        doClose(RET_CANCEL);
    }//GEN-LAST:event_jCancelarActionPerformed

    private void jAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAceptarActionPerformed
// TODO add your handling code here:
        doClose(RET_OK);
    }//GEN-LAST:event_jAceptarActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jAceptar;
    private javax.swing.JButton jCancelar;
    private javax.swing.JMenuItem jMenuItemAñadir;
    private javax.swing.JMenuItem jMenuItemBorrar;
    private javax.swing.JMenuItem jMenuItemConsultar;
    private javax.swing.JMenuItem jMenuItemEditar;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
    //
    // *********************************CAMPOS*********************************
    //
    private Conector _conector;
    //
    //********************************METODOS***********************************
    //
    
    //
    //**************************METODOS AUXILIARES******************************
    //    
    private void operaciones(int operacion){
        DialogForma mt;
        //String selectedId="";
        int selectedRow=this.jTable1.getSelectedRow();
        try{
            switch(operacion){
                case OP_ADD:
                    Forma forma=new Forma(this.getConector());
                    mt=new DialogForma(this,operacion,forma);
                    mt.setVisible(true);
                    if(mt.getReturnStatus()==DialogForma.RET_OK){
                        if(mt.getforma().insert()){
                            if(((String)this.jTable1.getValueAt(0,0)).equals("")){
                                this.jTable1.setValueAt(mt.getforma().getValue("orden"),0,0);
                                this.jTable1.setValueAt(mt.getforma().getId(),0,1);
                                this.jTable1.setValueAt(mt.getforma(),0,2);
                                this.jTable1.setValueAt(mt.getforma(),0,3);
                                this.jTable1.setValueAt(mt.getforma().getValue("formula"),0,4);
                                this.jTable1.setValueAt(mt.getforma().getValue("grupo_id"),0,5);
                            }else{
                                forma=mt.getforma();
                                Object[] fila={forma.getValue("orden"),forma.getId(),forma,forma,forma.getValue("formula"),forma.getValue("grupo_id")};
                                ((DefaultTableModel)this.jTable1.getModel()).addRow(fila);
                            }
                        }
                    }
                    break;
                case OP_EDIT:
                    if(selectedRow>-1){
                        forma=(Forma)this.jTable1.getValueAt(selectedRow,2);
                        mt=new DialogForma(this,operacion,forma);
                        mt.setVisible(true);
                        if(mt.getReturnStatus()==DialogForma.RET_OK){
                            if(mt.getforma().update()){
                                forma=mt.getforma();
                                ((DefaultTableModel)this.jTable1.getModel()).setValueAt(forma.getValue("orden"),selectedRow,0);
                                ((DefaultTableModel)this.jTable1.getModel()).setValueAt(forma.getId(),selectedRow,1);
                                ((DefaultTableModel)this.jTable1.getModel()).setValueAt(forma,selectedRow,2);
                                ((DefaultTableModel)this.jTable1.getModel()).setValueAt(forma,selectedRow,3);
                                ((DefaultTableModel)this.jTable1.getModel()).setValueAt(forma.getValue("formula"),selectedRow,4);
                                ((DefaultTableModel)this.jTable1.getModel()).setValueAt(forma.getValue("grupo_id"),selectedRow,5);
                            }
                        }
                    }
                    break;
                case OP_VIEW:
                    if(selectedRow>-1){
                        forma=(Forma)this.jTable1.getValueAt(selectedRow,2);
                        mt=new DialogForma(this,operacion,forma);
                        mt.setVisible(true);
                        break;
                    }
                case OP_DELETE:
                    if(selectedRow>-1){
                        forma=(Forma)this.jTable1.getValueAt(selectedRow,2);
                        if(forma.delete()){
                            if(selectedRow==0){
                                this.jTable1.setValueAt("",0,0);
                                this.jTable1.setValueAt("",0,1);
                                this.jTable1.setValueAt("",0,2);
                                this.jTable1.setValueAt("",0,3);
                                this.jTable1.setValueAt("",0,4);
                                this.jTable1.setValueAt("",0,5);
                            }else{
                                ((DefaultTableModel)this.jTable1.getModel()).removeRow(selectedRow);
                            }
                        }
                    }
                    break;
            }
        }catch(SQLException ex){
            ErrorDialog.manejaError(ex,false);
        }
    }
    
    private void refresca(){
        try {
            this.jTable1.setModel(new DefaultTableModel() {
                @Override
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return false;
                }
            });

            this.jTable1.setRowHeight(150);
            String[] columnNamesDiametro = {"Orden","Id", "Nombre", "Esquema","Formula","Grupo"};
            Forma forma=new Forma(this.getConector());
            ((DefaultTableModel) this.jTable1.getModel()).setColumnIdentifiers(columnNamesDiametro);

            for (Forma this_forma :forma.find("orden")) {
                Object[] fila = {this_forma.getValue("orden"),this_forma.getValue("id"), this_forma, this_forma, this_forma.getValue("formula"),this_forma.getValue("grupo_id")};
                ((DefaultTableModel) this.jTable1.getModel()).addRow(fila);
            }
            if(this.jTable1.getRowCount()==0){
                Object[] fila={"","","","","","",""};
                ((DefaultTableModel)this.jTable1.getModel()).addRow(fila);
            }
            this.setColumnWidth(0,0);
            this.setColumnWidth(1,0);
            this.setColumnWidth(2,50);
            this.setColumnWidth(3,150);
            this.jTable1.getColumnModel().getColumn(3).setCellRenderer(new JFormaTableCellRenderer());
            this.setColumnWidth(4,50);
            this.setColumnWidth(5,50);
        } catch (SQLException ex) {
            ErrorDialog.manejaError(ex);
        }
        this.jTable1.setUI(new DragDropRowTableUIOrdered());
    }
    private void setColumnWidth(int column,int width){
        this.jTable1.getColumnModel().getColumn(column).setPreferredWidth(width);
        this.jTable1.getColumnModel().getColumn(column).setMinWidth(width);
        this.jTable1.getColumnModel().getColumn(column).setMaxWidth(width);
        this.jTable1.getColumnModel().getColumn(column).setWidth(width);
    }
   
    private void doClose(int retStatus) {
        dispose();
    }    
    /**
     * @return the _conector
     */
    public Conector getConector() {
        return _conector;
    }

    /**
     * @param conector the _conector to set
     */
    public void setConector(Conector conector) {
        this._conector = conector;
    }
}
